const { LinValidator, Rule } = require('../../core/linValidator');
const { User } = require('../models/user');
const { loginType } = require('../lib/enum')

class IntValidator extends LinValidator {
    constructor() {
        super()
        this.id = [
            new Rule('isInt', '需要是正整数', { min: 1 }),
        ]
    }
}

class RegisterValidater extends LinValidator {
    constructor() {
        super()
        this.email = [
            new Rule('isEmail', '邮箱不符合规范')
        ]
        this.password1 = [
            new Rule('isLength', '至少6个字符,最多32个字符', {
                min: 6,
                max: 32
            }),
        ]
        this.password2 = this.password1,

        this.nickname = [
            new Rule('isLength', '至少4个字符,最多32个字符', {
                min: 4,
                max: 32
            })
        ]
    }

    validatePassword(vals) {
        const psw1 = vals.body.password1
        const psw2 = vals.body.password2
        if (psw1 !== psw2) {
            throw new Error('两个密码必须相同')
        }
    }
    async validateEmail(vals) {
        const email = vals.body.email
        const user = await User.findOne({
            where: {
                email,
            }
        })
        if (user) {
            throw new Error('Email已经存在')
        }
    }
}

class TokenValidator extends LinValidator {
    constructor() {
        super()
        this.account = [
            new Rule('isLength', '不符合账号规则', {
                min: 4,
                max: 32
            })
        ]
        this.secret = [
            new Rule('isOptional'),
            new Rule('isLength', '至少6个字符', {
                min: 6,
                max: 128
            })
        ]
    }

    // 校验登陆类型参数是否合法 
    validateLoginType(vals) {
        if (!vals.body.type) {
            throw new Error('type是必填参数')
        }
        if (!loginType.isThisType(vals.body.type)) {
            throw new Error('type参数不合法')
        }
    }
}

class NotEmpty extends LinValidator {
    constructor() {
        super()
        this.token = [
            new Rule('isLength', '不允许为空', { min: 1 })
        ]
    }
}

module.exports = {
    IntValidator,
    RegisterValidater,
    TokenValidator,
    NotEmpty

}